package com.pool.store;

import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.http.HttpResponse;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import com.pool.common.Lists;
import com.pool.store.gdata.GDataFactory;

/**
 * Interface for GData XML response processors.
 * 
 * @author claveld@gmail.com (David Clavel)
 */
public class XmlResponseProcessor<E> {

  private final GDataFactory<E> elementsFactory;
  
  private List<E> elements;
  
  public XmlResponseProcessor(GDataFactory<E> elementsFactory) {
    this.elementsFactory = elementsFactory;
  }

  public boolean process(HttpResponse response) {
    elements = Lists.newArrayList();
    SpreadsheetsXmlHandler<E> handler = new SpreadsheetsXmlHandler<E>(elementsFactory);
    try {
      /* Get a SAXParser from the SAXPArserFactory. */ 
      SAXParserFactory spf = SAXParserFactory.newInstance(); 
      SAXParser sp = spf.newSAXParser(); 

      /* Get the XMLReader of the SAXParser we created. */ 
      XMLReader xr = sp.getXMLReader(); 
      /* Create a new ContentHandler and apply it to the XML-Reader*/ 
      xr.setContentHandler(handler); 

      /* Parse the xml-data from our URL. */
      xr.parse(new InputSource(response.getEntity().getContent())); 
      /* Parsing has finished. */ 
    } catch (Exception e) {
      e.printStackTrace();
      return false;
    }

    elements.addAll(handler.getAll());
    return true;
  }

  public List<E> getList() {
    return elements;
  }
}